#include <config.h>
#include <stdio.h>
#include <board.h>
#include "bare_uart.h"
#include "bare_std.h"

int puts(const char *s)
{
	int i = 0;
	while (*s) {
		i++;
		serial_putc(*s);
		s++;
	}
	return i;
}

int putchar(int c)
{
	serial_putc(c);
	return 1;
}

int exit(int n)
{
	printf("exit: %n\n", n);
	while (1);
	return 1;
}

void _assert(int n, char *s)
{
	if (n == 0) {
		printf("assert: %s\n", s);
	}
}

void *b_malloc(size_t size, unsigned long offset)
{
	unsigned long long p = (offset + MEM_BASE_ADDR);
	unsigned long long mem_base_addr = MEM_BASE_ADDR;
	unsigned long long mem_size = MEM_SIZE;
	unsigned long long stack_addr = STACK_ADDR;
	unsigned long long stack_size = STACK_SIZE;
	if (p % 8 != 0) {
		p = (p >> 3) + 1;
		p = p << 3;
	}

	printf("available malloc mem space offset [0x%lx:0x%lx]\n", MOV_MEM_SIZE, (STACK_ADDR - STACK_SIZE));
	printf("debug: %lx\n", p);
	if (p > (mem_base_addr + mem_size)) {
		printf("error malloc size greater than memsize\n");
	} else if (p < (mem_base_addr + MOV_MEM_SIZE)) {
		printf("error protected mem, can't malloc\n");
	} else if (p > (stack_addr - stack_size)) {
		printf("error stack mem space: \n");
	} else {
		if (p % 8 != 0) {
			printf("malloc mem addr not align 8 bytes\n");
		}
		printf("malloc mem addr: 0x%p\n", (void*)p);
		return (void*)p;
	}
	exit(-1);
	return NULL;
}
